package com.smarthospital.common.util;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.smarthospital.contants.SHConst;
import com.smarthospital.entity.pojo.User;
import org.springframework.util.Base64Utils;

import java.util.Calendar;
import java.util.Map;

/**
 * create by sym  2021/4/24 10:04.
 */
public class JWTUtil {

    // 用于JWT进行签名加密的秘钥
    private static String SECRET = "code-duck-*%#@*!&";

    /**
     * @Param: 传入需要设置的payload信息
     * @return: 返回token
     */
    public static String generateToken(Map<String, String> map) {
        JWTCreator.Builder builder = JWT.create();

        // 将map内的信息传入JWT的payload中
        for (Map.Entry<String, String> entry : map.entrySet()) {
            builder.withClaim(entry.getKey(), entry.getValue());
        }

        // 设置JWT令牌的过期时间为60
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE, 60);
        builder.withExpiresAt(instance.getTime());

        // 设置签名并返回token
        return builder.sign(Algorithm.HMAC256(SECRET)).toString();
    }

    /**
     * @Param: 传入token
     * @return:
     */
    public static void verify(String token) {
        JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }

    /**
     * @Param: 传入token
     * @return: 解密的token信息
     */
    public static DecodedJWT getTokenInfo(String token) {
        return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }

    public static void main(String[] args) {
        byte[] bytes = Base64Utils.decodeFromString("eyJyZWdpc3RlcklkIjoiY2M2N2Y1YmViYmI5NDUxMzljMDQyYjFiNzFlNzFmMzIiLCJpZCI6IjM4IiwiZXhwIjoxNjIwNTYyNjQ3LCJvcHBlbklkIjoib3U2eTY1RXFoMnB5Q2Z2dERLeUFRN2dEV0IyZyJ9");
        String s = new String(bytes);
        User user = JSONObject.parseObject(s, User.class);
    }
    public  static <T> T getObject(String  payload,Class<T> clazz ){
        JSONObject jsonObject = JSONObject.parseObject(payload);
        String jsonObjectString = jsonObject.getString(SHConst.JWT_PAYLOD_KEY);
        T t = JSONObject.parseObject(jsonObjectString, clazz);
        return t;
    }
}
